const doms = {
    imgs: document.querySelector('.swiper-items'),
    indexs: document.querySelectorAll('.swiper-indexs li'),
    prev: document.querySelector('.swiper-prev'),
    next: document.querySelector('.swiper-next')
};

const delay = 3000;  // 轮播间隔
let currIndex = 0;   // 当前图片的索引
let timer;           // 定时器
const count = doms.indexs.length; // 图片数

// 处理图片滑动
function moveTo(index) {
    let diffIndex = currIndex - index;

    // 快速跳转逻辑
    if (Math.abs(diffIndex) === 2) {
        const direction = diffIndex === 2 ? '100%' : `-${count}00%`;
        doms.imgs.style.transform = `translateX(${direction})`;
        doms.imgs.style.transition = 'none';
        doms.imgs.clientHeight;  // 强制渲染
    }

    // 正常过渡动画
    doms.imgs.style.transition = 'transform .5s ease';
    doms.imgs.style.transform = `translateX(-${index}00%)`;

    // 更新索引高亮
    document.querySelector('.swiper-indexs li.active').classList.remove('active');
    doms.indexs[index].classList.add('active');

    currIndex = index;
}

// 自动轮播
function startSwiper() {
    timer = setInterval(rightMove, delay);
}

// 停止轮播
function stopSwiper() {
    clearInterval(timer);
}

// 鼠标悬停时停止轮播
doms.imgs.addEventListener('mouseenter', stopSwiper);
doms.imgs.addEventListener('mouseleave', startSwiper);

// index悬停
doms.indexs.forEach((item, index) => {
    item.addEventListener('mouseenter', () => {
        stopSwiper();
        moveTo(index);
    });
    item.addEventListener('mouseleave', startSwiper);
});

// 克隆第一张和最后一张图片
function clone() {
    const first = doms.imgs.firstElementChild.cloneNode(true);
    const last = doms.imgs.lastElementChild.cloneNode(true);

    doms.imgs.appendChild(first);
    doms.imgs.insertBefore(last, doms.imgs.firstElementChild);

    last.style.position = 'absolute';
    last.style.transform = `translateX(-110%)`;
}

clone();

// 向右移动
function rightMove() {
    if (currIndex === count - 1) {
        doms.imgs.style.transform = `translateX(100%)`;
        doms.imgs.style.transition = 'none';
        doms.imgs.clientHeight;  // 强制渲染
        moveTo(0);
    } else {
        moveTo(currIndex + 1);
    }
}

// 向左移动
function leftMove() {
    if (currIndex === 0) {
        doms.imgs.style.transform = `translateX(-${count}00%)`;
        doms.imgs.style.transition = 'none';
        doms.imgs.clientHeight;  // 强制渲染
        moveTo(count - 1);
    } else {
        moveTo(currIndex - 1);
    }
}

// 按钮点击
doms.prev.addEventListener('click', () => {
    console.log('上一张');
    stopSwiper();
    leftMove();
    startSwiper();
});

doms.next.addEventListener('click', () => {
    console.log('下一张');
    stopSwiper();
    rightMove();
    startSwiper();
});

// 启动自动轮播
startSwiper();